# views.py 
 
from . import blue #
from .models import User
from flask import Response, request, jsonify
from flask.views import MethodView
from common.status_code import StatusCode
from common.json_response import JsonResponse
from common.pagination import Pagination
from common.query_filter import QueryFilter

class UserView(MethodView):
    def get(self, user_id=None):
        """获取单个用户信息或用户列表"""
        if user_id is None:
            # 获取用户列表
            try:
                params = {
                    'keyword': request.args.get('keyword', ''),
                    'status': request.args.get('status'),
                    'min_age': request.args.get('min_age', type=int),
                    'max_age': request.args.get('max_age', type=int),
                    'roles': request.args.getlist('roles'),
                    'page': int(request.args.get('page', 1)),
                    'per_page': int(request.args.get('per_page', 10))
                }
                query = (QueryFilter(User.query)
                    .fuzzy_match(['name', 'email'], params['keyword'])
                    .exact_match(status=params['status'])
                    .range_filter('age', params['min_age'], params['max_age'])
                    .in_filter('role', params['roles'])
                    .apply_filters())
                pagination = Pagination(query, params['page'], params['per_page'])
                
                return JsonResponse.success(
                    data=pagination.to_dict(),
                    message="查询成功"
                )
            except ValueError as e:
                return JsonResponse.error(
                    message="参数格式错误",
                    status=StatusCode.BAD_REQUEST.value
                )
            except Exception as e:
                return JsonResponse.error(
                    message="查询失败",
                    status=StatusCode.INTERNAL_SERVER_ERROR.value
                )
        else:
            # 获取单个用户
            user = User.get_by_id(user_id)
            if not user:
                return JsonResponse.error(
                    message=f'user {StatusCode.NOT_FOUND.get_status_message()}',
                    status=StatusCode.NOT_FOUND.value
                )
            return JsonResponse.success(data=user.to_dict())

    def post(self):
        """创建用户"""
        try:
            data = request.get_json()
            if not data:
                return JsonResponse.error(
                    message="请求数据不能为空",
                    status=StatusCode.BAD_REQUEST.value
                )

            required_fields = ['name', 'email', 'password']
            missing_fields = [field for field in required_fields if field not in data]
            if missing_fields:
                return JsonResponse.error(
                    message=f"缺少必要字段: {', '.join(missing_fields)}",
                    status=StatusCode.BAD_REQUEST.value
                )

            user = User(**data)
            user.add()
            return JsonResponse.success(
                data=user.to_dict(),
                message="创建成功"
            )
        except Exception as e:
            return JsonResponse.error(
                message=str(e),
                status=StatusCode.BAD_REQUEST.value
            )

    def put(self, user_id):
        """更新用户信息"""
        try:
            user = User.get_by_id(user_id)
            if not user:
                return JsonResponse.error(
                    message="用户不存在",
                    status=StatusCode.NOT_FOUND.value
                )

            data = request.get_json()
            if not data:
                return JsonResponse.error(
                    message="请求数据不能为空",
                    status=StatusCode.BAD_REQUEST.value
                )

            # 禁止修改的字段
            forbidden_fields = ['id', 'password_hash']
            for field in forbidden_fields:
                data.pop(field, None)

            user.update(**data)
            return JsonResponse.success(
                data=user.to_dict(),
                message="更新成功"
            )
        except Exception as e:
            return JsonResponse.error(
                message=str(e),
                status=StatusCode.BAD_REQUEST.value
            )

    def delete(self, user_id):
        """删除用户"""
        try:
            user = User.get_by_id(user_id)
            if not user:
                return JsonResponse.error(
                    message="用户不存在",
                    status=StatusCode.NOT_FOUND.value
                )

            user.delete()
            return JsonResponse.success(message="删除成功")
        except Exception as e:
            return JsonResponse.error(
                message=str(e),
                status=StatusCode.INTERNAL_SERVER_ERROR.value
            )

# 注册路由
user_view = UserView.as_view('user_api')
blue.add_url_rule('/list', view_func=user_view, defaults={'user_id': None}, methods=['GET'])
blue.add_url_rule('', view_func=user_view, methods=['POST'])
blue.add_url_rule('/<int:user_id>', view_func=user_view, methods=['GET', 'PUT', 'DELETE'])